<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Cache;
use think\Config;

/**
 * 抢答接口📝
 */
class Race extends Api
{
    // protected $noNeedLogin = ['get_subj'];
    protected $noNeedLogin = ['get_ranking','clear_race_data','get_ranking2'];
    protected $noNeedRight = ['*'];


    /**
     * 提交抢答答案（单题）
     *
     * @param string $id 题目id
     * @param string $answer 答案内容
     * 
     * @return void
     */
    public function submit_answers($id,$answer,$end=null)
    {   

        if($end){
            $key = 'race_subj_end'.$this->auth->id;
            Cache::set($key,time());
            Cache::tag('race_subj_end',[$key]);
        }

        if($this->verify_the_answer($id,$answer)){
            //存储答题 
            $data['user_id'] = $this->auth->id;
            $data['subj_id'] = $id;
            $data['answer'] = $answer;
            $data['date'] = date('Y_m_d');
            $res = Db::name('race_subj')->where($data)->find();
            if($res){
                $this->error('该题已回答');
            }

            $data['time'] = time();

            
            $ID = Db::name('race_subj')->insertGetId($data);
            if($ID){
                $user_r = Db::name('ranking')->where('user_id',$this->auth->id)->find();
                $race_time = strtotime(Config::get('site.race_time'));//不要缓存
                if($user_r){
                    Db::name('ranking')->where('user_id',$this->auth->id)->setInc('yes', 1);
                    Db::name('ranking')->where('user_id',$this->auth->id)->setField('sec', $data['time']-$race_time);//Cache::get('race_time'));

                    if($end){
                        $res_data = Db::name('ranking')->where('user_id',$this->auth->id)->find();
                        $this->success('回答完成',$res_data,4);
                    }

                }else{
                    $ranking['user_id'] = $this->auth->id;
                    $ranking['yes'] = 1;
                    $ranking['sec'] = $data['time']-$race_time;//Cache::get('race_time');
                    Db::name('ranking')->insert($ranking);
                }
            }
            // $key = date('Y_m_d').'_ranking';
            // $data = Cache::set($key,$id);

            // $get_poster = $this->get_poster($this->auth->id);//创建一张海报
            
            $this->success('回答正确');
        }else{
            $this->error('需要再接再厉');
        }
    }


    /**
     * 获取比赛题目（25号）
     *
     * @param integer $limit 数量默认10
     * @return void
     */
    public function get_race_subj($limit=10)
    {

        // if(!Cache::get('race_time')){
        //     Cache::set('race_time',strtotime(Config::get('site.race_time')),60);
        // }
        // if(Cache::get('race_time')>time()){
        //     $this->error('剩余倒计时'.(Cache::get('race_time')-time()).'秒');
        // }
        $race_time = strtotime(Config::get('site.race_time'));
        if($race_time>time()){
            $this->error('剩余倒计时'.($race_time-time()).'秒');
        }

        if(Cache::get('race_subj_end'.$this->auth->id)){
            $this->error('已参与过该活动');
        }

        $data = Cache::get('all_race_subj');
        if(!$data){
            Cache::set('all_race_subj',DB::name('subj')->where('subj_status','2')->limit($limit)->field('answer,subj_status,createtime',true)->select(),6000);
            $data = Cache::get('all_race_subj');
        }

        
        //获取数量

        // if($limit==1){
        //     $new_data =$data[array_rand($data,$limit)];
        // }else{
        //     $ids = array_rand($data,$limit);
        //     $new_data = array();
        //     foreach($ids as $key => $val){
        //         $new_data[] = $data[$val];
        //     }
        // }
        // $this->success('ok',$new_data);

        $this->success('ok',$data);
       
        
    }


    /**
     * 验证答案
     */
    public function verify_the_answer($id,$answer)
    {
        $subj = Db::name('subj')->find($id);
        if(!$subj){
            $this->error('没有此题');
        }

        if($answer==$subj['answer']){
            return true;
        }else{
            return false;
        }
    }


    /**
     * 获取排名
     *
     * @return void
     */
    public function get_ranking($limit=100)
    {
        // Cache::clear('ranking_user'); 
        $key = 'ranking_user';
        if(!Cache::get($key)){
            $list = Db::name('ranking')
                ->order('yes desc')
                ->order('sec asc')
                ->limit($limit)
                ->select();
            foreach ($list as &$val) {
                $val['user'] = Db::name('user')->where('id',$val['user_id'])->field('nickname,avatar,id')->find();
                if($val['sec']>60){
                    $fen = round($val['sec']/60,0);
                    $sec = $val['sec']%60;
                   
                    $val['sec'] = $fen.'分'.$sec;

                }
                
            }

            Cache::set($key,$list,10);
            Cache::tag($key,[$key]);
        }

        $this->success('ok',Cache::get($key));
        
    }

    /**
     * 获取排名
     *
     * @return void
     */
    public function get_ranking2($limit=100)
    {
        // Cache::clear('ranking_user'); 
        $key = 'ranking_user';
        if(!Cache::get($key)){
            $list = Db::name('ranking')
                ->order('yes desc')
                ->order('sec asc')
                ->limit($limit)
                ->select();
            foreach ($list as &$val) {
                $val['user'] = Db::name('user')->where('id',$val['user_id'])->field('nickname,avatar,id')->find();
                if($val['sec']>60){
                    $fen = round($val['sec']/60,0);
                    $sec = $val['sec']%60;
                   
                    $val['sec'] = $fen.'分'.$sec;

                }
                
            }

            Cache::set($key,$list,5);
            Cache::tag($key,[$key]);
        }

        $this->success('ok',Cache::get($key));
        
    }

    /**
     * 清楚抢答数据 不需要调此接口
     *
     * @param Type $var
     * @return void
     */
    public function clear_race_data()
    {

     
        if(strtotime(Config::get('site.race_time'))<time()){
            if(!Config::get('site.api_debug')){
                $this->error('抢答时间已过,不能清除');
            }
            // 
        }

        $res = Db::name('race_subj')->where('id','>',0)->delete();
            Db::name('ranking')->where('id','>',0)->delete();
        Cache::clear('ranking_user'); 
        Cache::clear('race_subj_end'); 

        // Cache::clear('submit_subj'); //活动预热提交等
        

        $this->success('清除排行成功',$res);
    }


}